package com.bhatni.taskmanager;

import com.bhatni.taskmanager.task.CopyFileTask;
import com.bhatni.taskmanager.schedule.PeriodicSchedule;
import com.bhatni.taskmanager.schedule.CalendarSchedule;
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

public class ScheduledCopy {

    static void help() {
        System.out.println("Syntax: ScheduledCopy <ScheduledCopy XML config file>");
    }

    public static void main(String[] args) {
        if (args.length < 1) {
            help();
            return;
        }

        TaskManager tm = new TaskManager();

        Document doc = null;
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            doc = builder.parse(args[0]);

        } catch (Exception e) {
            System.out.println("Error: Unable to load " + args[0] + ". "
                    + e.getMessage());
            return;
        }
        XPath xpath = XPathFactory.newInstance().newXPath();
        String expression = "/ScheduledCopy/SourceDir/text()";
        String sourceDir;
        try {
            sourceDir = (String) xpath.evaluate(expression, doc,
                    XPathConstants.STRING);
        } catch (XPathExpressionException e) {
            System.out.println("Error: Source folder in " + args[0]
                    + " not defined.");
            return;
        }
        expression = "/ScheduledCopy/TargetDir/text()";
        String targetDir;
        try {
            targetDir = (String) xpath.evaluate(expression, doc,
                    XPathConstants.STRING);
        } catch (XPathExpressionException e) {
            System.out.println("Error: Target folder in " + args[0]
                    + " not defined.");
            return;
        }
        expression = "/ScheduledCopy/File";
        NodeList files;
        try {
            files = (NodeList) xpath.evaluate(expression, doc,
                    XPathConstants.NODESET);
        } catch (XPathExpressionException e) {
            System.out.println("Error: No files specified in " + args[0]);
            return;
        }
        for (int i = 0; (files != null) && (i < files.getLength()); i++) {
            Element file = (Element) files.item(i);
            String name = file.getAttribute("Name");
            String disabled = file.getAttribute("Disabled");

            if (disabled.compareToIgnoreCase("Yes") != 0) {
                expression = "SourceSubDir/text()";
                String sourceSubDir;
                try {
                    sourceSubDir = (String) xpath.evaluate(expression, file,
                            XPathConstants.STRING);
                } catch (XPathExpressionException e) {
                    sourceSubDir = "";
                }
                expression = "TargetSubDir/text()";
                String targetSubDir;
                try {
                    targetSubDir = (String) xpath.evaluate(expression, file,
                            XPathConstants.STRING);
                } catch (XPathExpressionException e) {
                    targetSubDir = "";
                }

                StringBuffer sourcePath = new StringBuffer(sourceDir);
                if (!sourceDir.endsWith(File.separator)) {
                    sourcePath.append(File.separator);
                }
                if (sourceSubDir.length() > 0) {
                    sourcePath.append(sourceSubDir);
                    sourcePath.append(File.separator);
                }
                sourcePath.append(name);

                StringBuffer targetPath = new StringBuffer(targetDir);
                if (!targetDir.endsWith(File.separator)) {
                    targetPath.append(File.separator);
                }
                if (targetSubDir.length() > 0) {
                    targetPath.append(targetSubDir);
                    targetPath.append(File.separator);
                }
                targetPath.append(name);

                expression = "PeriodicSchedule";
                NodeList schedules = null;
                try {
                    schedules = (NodeList) xpath.evaluate(expression, file,
                            XPathConstants.NODESET);
                } catch (XPathExpressionException localXPathExpressionException1) {
                }
                for (int j = 0; (schedules != null) && (j < schedules.getLength()); j++) {
                    CopyFileTask cpt = new CopyFileTask();

                    cpt.setSourceLocation(sourcePath.toString());
                    cpt.setDestinationLocation(targetPath.toString());

                    PeriodicSchedule sch = new PeriodicSchedule();

                    Element schedule = (Element) schedules.item(j);
                    String RPS = schedule.getAttribute("RPS");
                    if (RPS.length() > 0) {
                        sch.setRps(Float.parseFloat(RPS));
                    }
                    cpt.setSchedule(sch);
                    tm.addTask(cpt);
                }

                expression = "CalenderSchedule";
                schedules = null;
                try {
                    schedules = (NodeList) xpath.evaluate(expression, file,
                            XPathConstants.NODESET);
                } catch (XPathExpressionException localXPathExpressionException2) {
                }
                for (int j = 0; (schedules != null) && (j < schedules.getLength()); j++) {
                    CopyFileTask cpt = new CopyFileTask();
                    cpt.setSourceLocation(sourcePath.toString());
                    cpt.setDestinationLocation(targetPath.toString());

                    CalendarSchedule sch = new CalendarSchedule();

                    Element schedule = (Element) schedules.item(j);
                    String year = schedule.getAttribute("Year");
                    if (year.length() > 0) {
                        sch.setYear(Integer.parseInt(year));
                    }
                    String month = schedule.getAttribute("Month");
                    if (month.length() > 0) {
                        sch.setMonth(Integer.parseInt(month));
                    }
                    String daytypestr = schedule.getAttribute("DayType");
                    int daytype = 5;
                    if (daytypestr.compareToIgnoreCase("DayOfWeek") == 0) {
                        daytype = 7;
                    } else if (daytypestr.compareToIgnoreCase("DayOfYear") == 0) {
                        daytype = 6;
                    }
                    sch.setDayType(daytype);
                    String day = schedule.getAttribute("Day");
                    if (day.length() > 0) {
                        sch.setDay(Integer.parseInt(day));
                    }
                    String hour = schedule.getAttribute("Hour");
                    if (hour.length() > 0) {
                        sch.setHour(Integer.parseInt(hour));
                    }
                    String minute = schedule.getAttribute("Minute");
                    if (minute.length() > 0) {
                        sch.setMinute(Integer.parseInt(minute));
                    }
                    String second = schedule.getAttribute("Second");
                    if (second.length() > 0) {
                        sch.setSecond(Integer.parseInt(second));
                    }
                    String millisecond = schedule.getAttribute("Millisecond");
                    if (millisecond.length() > 0) {
                        sch.setMillisecond(Integer.parseInt(millisecond));
                    }
                    cpt.setSchedule(sch);
                    tm.addTask(cpt);
                }
            }
        }
        tm.RunTasks();
        System.out.println("Done");
    }
}
